<template>
  <div v-if="type == 'pdf'">
    <!-- PDF 渲染区域 -->
    <div class="pdf-canvas-container  mt20">
      <canvas ref="pdfCanvas"></canvas>
    </div>
    <div class="text-right mt10">
      <el-button class="ml10" size="large" type="primary" @click="onPdfSize(1)">缩小</el-button>
      <el-button class="ml10" size="large" type="primary" @click="onPdfSize(2)">放大</el-button>
      <el-button class="ml10" size="large" type="success" :icon="RefreshLeft" @click="onPdfFlip(1)">翻转</el-button>
      <el-button class="ml10" size="large" type="success" :icon="RefreshRight" @click="onPdfFlip(2)">翻转</el-button>
      <el-button size="large" :disabled="currentPage === 1" @click="prevPage">　上一页</el-button>
      <el-button size="large" class="ml10" :disabled="currentPage === totalPages" @click="nextPage">下一页　</el-button>
      <el-text class="ml10">　第 {{ currentPage }} / {{ totalPages }} 页　</el-text>
      <el-button size="large" class="ml10" type="primary" @click="downloadPdf">下载</el-button>
    </div>
  </div>

  <div class="text-right" v-if="type == 'png' || type == 'jpg' || type == 'jpeg'">
    <p class="text-center pdf-canvas-container"><el-image v-if="pdfUrl" :src="pdfUrl" fit="contain" :style="{
        transform: `scale(${scale_img}) rotate(${rotation_img}deg)`,
        transition: 'transform 0.3s ease'
      }" class="min-w" /></p>
    <div class="mt10">
      <el-button class="ml10" size="large" type="primary" @click="onImgSize(1)">缩小</el-button>
      <el-button class="ml10" size="large" type="primary" @click="onImgSize(2)">放大</el-button>
      <el-button class="ml10" size="large" type="success" :icon="RefreshLeft" @click="onImgFlip(1)">翻转</el-button>
      <el-button class="ml10" size="large" type="success" :icon="RefreshRight" @click="onImgFlip(2)">翻转</el-button>
      <el-button size="large" class="ml10" type="primary" @click="downloadPdf">下载</el-button>
    </div>
    
  </div>
  
</template>

<script setup lang="ts">
import { ref, onUnmounted, watch } from 'vue';
import { RefreshLeft, RefreshRight} from '@element-plus/icons-vue'
import * as pdfjsLib from 'pdfjs-dist';
import 'pdfjs-dist/web/pdf_viewer.css';
// import LegacyWorker from 'pdfjs-dist/legacy/build/pdf.worker.min?url'
import LegacyWorker from '../assets/pdf.worker.min?url'
pdfjsLib.GlobalWorkerOptions.workerSrc = LegacyWorker
const type = ref('');

// 组件状态
const pdfUrl = ref('');
let pdfDoc:any = '';
const pdfCanvas = ref<HTMLCanvasElement | null>(null);
const loading = ref(false);
const error = ref('');
const currentPage = ref(1);
const totalPages = ref(0);
const scale = ref(1.0);
const rotation = ref(0) // 旋转角度（0、90、180、270）

const scale_img = ref(1.0)
const rotation_img = ref(0)

// 限制最小缩放比例
const minScale = 0.5
// 限制最大缩放比例
const maxScale = 2.0
// 缩放步长
const scaleStep = 0.1

// 加载 PDF 文件
const loadPdf = async () => {
  if (!pdfUrl.value.trim()) {
    error.value = '请输入有效的 PDF URL';
    return;
  }
  
  loading.value = true;
  error.value = '';
  
  try {
    // 检查 URL 是否有效
    const response = await fetch(pdfUrl.value, { method: 'HEAD' });
    if (!response.ok) {
      throw new Error(`无法访问 URL: ${response.status} ${response.statusText}`);
    }
    
    // 加载 PDF
    const loadingTask = pdfjsLib.getDocument({
      url: pdfUrl.value,
      cMapUrl: 'https://unpkg.com/pdfjs-dist@3.4.120/cmaps/',
      cMapPacked: true
    });
    
    pdfDoc = await loadingTask.promise;
    totalPages.value = pdfDoc.numPages;
    
    // 渲染第一页
    setTimeout(() => {
      renderPage(currentPage.value);
    }, 1000);
    
  } catch (err: any) {
    console.error('加载 PDF 失败:', err);
    error.value = err.message || '加载 PDF 失败';
  } finally {
    loading.value = false;
  }
};

// 渲染指定页面
const renderPage = async (pageNum: number) => {
  if (!pdfDoc || !pdfCanvas.value) return;
  
  try {
    let page = await pdfDoc.getPage(pageNum);
    
    // 设置 canvas 尺寸
    const viewport = page.getViewport({ scale: scale.value,rotation: rotation.value });
    pdfCanvas.value.height = viewport.height;
    pdfCanvas.value.width = viewport.width;
    
    // 渲染 PDF 页面
    const renderContext = {
      canvasContext: pdfCanvas.value.getContext('2d')!,
      viewport: viewport
    };
    
    await page.render(renderContext).promise;
    currentPage.value = pageNum;
  } catch (err: any) {
    console.error('渲染页面失败:', err);
    error.value = '渲染页面失败';
  }
};

// 导航控制
const prevPage = () => {
  if (currentPage.value > 1) {
    renderPage(currentPage.value - 1);
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    renderPage(currentPage.value + 1);
  }
};

// 下载 PDF
const downloadPdf = () => {
  if (!pdfUrl.value) return;
  
  const link = document.createElement('a');
  link.href = pdfUrl.value;
  link.download = pdfUrl.value.split('/').pop() || 'document.pdf';
  link.click();
};

const props = defineProps<{
    data:any
}>()

watch(props,()=>{
  pdfUrl.value = props.data
  if (!pdfUrl.value) return;
  type.value = pdfUrl.value.split('.').pop()?.toLowerCase() || '';
  if(type.value == 'pdf'){
    loadPdf()
  }
  
},{ immediate: true })

const onPdfFlip = (type:number) => {
  if(type == 2){
    rotation.value = (rotation.value + 90) % 360
    renderPage(currentPage.value)
  }else{
    rotation.value = (rotation.value - 90 + 360) % 360
    renderPage(currentPage.value)
  }
};

const onPdfSize = (type:number) => {
  if(type == 2){
    if (scale.value < maxScale) {
      scale.value += scaleStep
      renderPage(currentPage.value)
    }
  }else{
    if (scale.value > minScale) {
      scale.value -= scaleStep
      renderPage(currentPage.value)
    }
  }
  
};


const onImgSize = (type:number) => {
  if(type == 1){
    scale_img.value = Math.max(scale_img.value - 0.1, 0.5)
  }else{
    scale_img.value = Math.min(scale_img.value + 0.1, 3.0) // 最大缩放 3 倍
  }
};

const onImgFlip = (type:number) => {
  if(type == 1){
    rotation_img.value = (rotation_img.value - 90 + 360) % 360
  }else{
    rotation_img.value = (rotation_img.value + 90) % 360
  }
  
};



onUnmounted(() => {
  // 清理资源
  pdfDoc = null;
});
</script>

<style scoped>

.pdf-canvas-container {
  overflow: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  background-color: #f9f9f9;
  border-radius: 8px;
  height: calc(100vh - 14vh) !important;overflow-y: scroll;
}

canvas {
  display: block;
  margin: 0 auto;
  max-width: 100%;
}

::-webkit-scrollbar { width: 8px; /* 设置滚动条宽度 */ }
::-webkit-scrollbar-thumb { background-color: #a4a4a4; border-radius: 4px; /* 设置滑块圆角 */ }
::-webkit-scrollbar-track:hover { background-color: #f0f0f0; }
::-webkit-scrollbar-thumb:hover { background-color: #555; }

.min-w{min-width: 600px;}
</style>